package com.upsuns.protocol;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.upsuns.utils.Constants;

/**
 *@Description:<p>协议约定端</p>
 *@author 王旭
 *@time 2016-2-9 下午10:03:34
 */
public class ProtocolClient {
	
	private String address; //接收端地址
	
	private int port; //接收端端口
	
	private Socket socket;
	
	
	public ProtocolClient(String address) {
		this.address = address;
		this.port = Constants.PORT_BASE - 1; //默认文件传输端口
		try {
			socket = new Socket(address, port);
		} catch (IOException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 序列化protocol对象，发送至协议接收端
	 * @param protocol
	 */
	public void sentProtocol(Protocol protocol) {
		
		OutputStream os = null;
		
		ObjectOutputStream oos = null;
		try {
			os = socket.getOutputStream();
			
			oos = new ObjectOutputStream(os);
			oos.writeObject(protocol);
			oos.flush();
			
		} catch (IOException e) {
			System.out.println("协议传输失败");
			e.printStackTrace();
		} finally {
			try {
				oos.close();
				os.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
	}
	
	public boolean isConnected() {
		return socket.isConnected();
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	
}
